from paddleocr import PaddleOCR, draw_ocr
import os, sys
import argparse
import time

def create_ocr(use_cuda):
    # 模型路径下必须含有model和params文件
    det = './model/ch_ppocr_mobile_v1.1_det_infer'
    rec = './model/ch_ppocr_mobile_v1.1_rec_infer'
    cls = './model/ch_ppocr_mobile_v1.1_cls_infer'
    rec_char = './ppocr/utils/ppocr_keys_v1.txt'
    ocr = PaddleOCR(det_model_dir=det, rec_model_dir=rec, rec_char_dict_path=rec_char, cls_model_dir=cls, use_angle_cls=True, use_gpu=use_cuda, lang='ch')
    return ocr

def recongnize(img, ocr, is_show=False):
    img_path = img
    result = ocr.ocr(img_path, cls=True)
    for line in result:
        print(line)

    boxes = [line[0] for line in result]
    txts = [line[1][0] for line in result]
    scores = [line[1][1] for line in result]

    if is_show:
        # 显示结果
        from PIL import Image
        image = Image.open(img_path).convert('RGB')
        im_show = draw_ocr(image, boxes, txts, scores, font_path=os.path.abspath('./wqy-zenhei.ttc'))
        im_show = Image.fromarray(im_show)
        im_show.save('result.jpg')

    return txts, scores

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--use-cuda', action='store_true', default=False)
    parser.add_argument('-i', '--img')
    parser.add_argument('--show', action='store_true', default=False)
    args = parser.parse_args()

    sys.argv = [sys.argv[0]]

    ocr = create_ocr(args.use_cuda)

    bgn = time.time()
    txts, scores = recongnize(args.img, ocr, args.show)
    end = time.time()
    print(f'recongnize time: {end-bgn}s')
    for i in range(len(txts)):
        print('txt: {}, score: {}'.format(txts[i], scores[i]))
